/* Copyright 2013 ESRI
* 
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* 
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* 
* See the use restrictions at <your ArcGIS install location>/DeveloperKit10.2/userestrictions.txt.
* 
*/
package arcgissamples.mapbean;

import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

import com.esri.arcgis.beans.map.MapBean;
import com.esri.arcgis.carto.FeatureLayer;
import com.esri.arcgis.carto.IActiveView;
import com.esri.arcgis.carto.ILayer;
import com.esri.arcgis.carto.esriSelectionResultEnum;
import com.esri.arcgis.carto.esriViewDrawPhase;
import com.esri.arcgis.controls.IMapControlEvents2Adapter;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseDownEvent;
import com.esri.arcgis.geodatabase.QueryFilter;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

/**
 * This sample illustrates how to programatically select features on the Map Control using a QueryFilter.
 */
public class SelectFeaturesUsingQuery extends JFrame implements ActionListener
{
	static AoInitialize aoInit;
	JPanel topPanel = null;
	JPanel mainPanel = null;
	JPanel rightPanel = null;
	JPanel bottomPanel = null;
	JButton addLayerButton = null;
	JLabel queryTextLabel = null;
	JTextField queryTextField = null;
	JButton selectButton = null;
	MapBean mapBean = null;
	JTextArea help = null;
	String helpString = "1.Add a layer using addLayer button.\n" + "2. Enter the where clause in the text\n"
			+ "field provided\n\n" + "Example: If you add the States layer,\n"
			+ "then your Where clause to select California\n" + "state will be STATE_NAME='California'.\n\n"
			+ "Use the left mouse button to zoom in.\n" + "Use the right mouse button to pan.";

	public SelectFeaturesUsingQuery()
	{
		super("Attribute Query");
		buildFrame();
		setSize(600, 500);
		setVisible(true);
		initControl();
	}

	public void buildFrame()
	{
		topPanel = new JPanel();
		mainPanel = new JPanel();
		rightPanel = new JPanel();
		bottomPanel = new JPanel();

		topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
		mainPanel.setLayout(new BorderLayout(10, 10));
		bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));

		addLayerButton = new JButton("Add Data Layer");
		addLayerButton.addActionListener(this);
		topPanel.add(addLayerButton);

		queryTextLabel = new JLabel("Where Clause");
		queryTextField = new JTextField();
		selectButton = new JButton("Select Features");
		selectButton.addActionListener(this);
		bottomPanel.add(queryTextLabel);
		bottomPanel.add(Box.createHorizontalStrut(5));
		bottomPanel.add(queryTextField);
		bottomPanel.add(Box.createHorizontalStrut(5));
		bottomPanel.add(selectButton);

		help = new JTextArea();
		help.setText(helpString);
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		rightPanel.add(help);
		rightPanel.add(Box.createVerticalGlue());
		rightPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

		// Create map control add it to the center of the main panel.
		mapBean = new MapBean();
		mainPanel.add(topPanel, BorderLayout.NORTH);
		mainPanel.add(mapBean, BorderLayout.CENTER);
		mainPanel.add(rightPanel, BorderLayout.EAST);
		mainPanel.add(bottomPanel, BorderLayout.SOUTH);
		mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

		getContentPane().add(mainPanel, BorderLayout.CENTER);
	}

	/**
	 * Initilizes control creates and intializes member variables
	 */

	public void initControl()
	{
		try
		{
			mapBean.addIMapControlEvents2Listener(new MapControlListener());
		}
		catch (IOException ex)
		{
			System.out.println("Exception in initControl :" + ex);
			ex.printStackTrace();
		}

	}

	/**
	 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent event)
	 * @param event
	 */

	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource() == addLayerButton)
		{
			if (!loadFile())
			{
				return;
			}
		}

		if (event.getSource() == selectButton)
		{
			processQuery();
		}
	}

	/**
	 * To perform attribute query based on the user input
	 */

	void processQuery()
	{
		try
		{
			// Make sure that a layer has been added
			int layerCount = mapBean.getLayerCount();
			if (layerCount < 0)
			{
				JOptionPane.showMessageDialog(this, "Please add a feature layer first");
			}

			ILayer layer = null;
			FeatureLayer featureLayer = null;

			try
			{
				// Just use 1st layer
				layer = mapBean.getLayer(0);
				featureLayer = (FeatureLayer) layer;
				String queryString = queryTextField.getText();
				if (queryString != null || queryString.length() > 0)
				{
					// Do a query
					QueryFilter queryFilter = new QueryFilter();
					queryFilter.setWhereClause(queryString);
					featureLayer.selectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
					IActiveView activeView = mapBean.getActiveView();
					activeView.partialRefresh(esriViewDrawPhase.esriViewGeoSelection, layer, null);
				}

			}
			catch (IOException ex)
			{
				JOptionPane.showMessageDialog(this, "Please add a feature layer first");
			}

		}
		catch (IOException ex1)
		{
			ex1.printStackTrace();
		}

	}

	/**
	 * Method loadFile loads the specified mxd file
	 */
	public boolean loadFile()
	{
		FileDialog fileDialog = new FileDialog(this, "Select layer (.lyr) file", FileDialog.LOAD);
		fileDialog.setVisible(true);
		String fileChosen = fileDialog.getDirectory() + fileDialog.getFile();
		try
		{
			this.mapBean.addLayerFromFile(fileChosen, 0);
		}
		catch (Exception ex)
		{
			System.out.println("Couldn't add layer using " + fileChosen);
			return false;
		}
		return true;
	}

	/**
	 * Description: Class which extends map control event class IMapControlEvents2Adapter
	 * 
	 * @see com.esri.arcgis.beans.map.IMapControlEvents2Adapter
	 */

	class MapControlListener extends IMapControlEvents2Adapter
	{

		/**
		 * @see com.esri.arcgis.beans.map.IMapControlEvents2Adapter#onMouseDown(IMapControlEvents2OnMouseDownEvent
		 *      theEvent)
		 * @param theEvent
		 */

		public void onMouseDown(IMapControlEvents2OnMouseDownEvent theEvent)
		{
			try
			{
				// If left mouse button then zoom in
				if (theEvent.getButton() == 1)
				{
					mapBean.setExtent(mapBean.trackRectangle());
				}
				else if (theEvent.getButton() == 2)
				{
					mapBean.pan();
				}

			}
			catch (Exception ex)
			{
				System.out.println("Exception in MapControlListener#onMouseDown : " + ex);
				ex.printStackTrace();
			}

		}

	} // End of MapControlListener class

	/**
	 * Main program to start the program execution.
	 * 
	 * @param s
	 */

	public static void main(String s[])
	{
		try
		{
			EngineInitializer.initializeVisualBeans();
			// Set the system look and feel
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			
			aoInit = new AoInitialize();
			
			initializeArcGISLicenses(aoInit);

			SelectFeaturesUsingQuery attributeQuery = new SelectFeaturesUsingQuery();
			attributeQuery.setDefaultCloseOperation(SelectFeaturesUsingQuery.EXIT_ON_CLOSE);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	static void initializeArcGISLicenses(AoInitialize aoInit) {
		try {
			if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) 
					== esriLicenseStatus.esriLicenseAvailable)
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
			else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic) 
					== esriLicenseStatus.esriLicenseAvailable)
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
			else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeStandard) 
					== esriLicenseStatus.esriLicenseAvailable)
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeStandard);
			else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeAdvanced) 
					== esriLicenseStatus.esriLicenseAvailable)
				aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
